<?php

namespace BasicAdmin\Modules\User\Controllers;


use BasicAdmin\Models\UserModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class IndexController extends Controller
{
    public function index(Content $content) {

        $list = UserModel::select('*', ['state' => 0]);
        $gridModel = new \App\Pockets\GridDataModel($list, 30, [
            'perPage' => 20
        ]);
        $grid = Admin::grid($gridModel, function (Grid $grid) {
                $grid->column('id', '职工ID');
                $grid->column('name', '姓名');
                $grid->column('account', '账号');
        });
        return $content
            ->title('职工列表')
            ->row($grid);
    }

    public function create(Content $content, $id = 0) {

        $info = $id ? UserModel::get('*', ['id' => $id]) : [];
        $form = new Form($info);
//        $form->action('/admin/user/create');
        $form->text('name', '姓名')->required();
        $form->text('account', '账号');
        $form->password('password', '密码');
        $form->image('avatar', '头像');
        $form->radio('state', '状态')->options();
        return $content
            ->title('新增职工')
            ->description(" ")
            ->breadcrumb(['text' => '品牌内部清单'])
            ->body($form);
    }

    public function save(Request $request, $id = 0)
    {
        $status = true;
        $message = "操作成功";
        try {
            $data = [
                'name' => $request->input('name', ''),
                'account' => $request->input('account', ''),
                'password' => $request->input('password', ''),
                'avatar' => $request->input('avatar', ''),
                'state' => $request->input('state', 0),
            ];
            $id ? UserModel::update($data + ['update_at' => date("Y-m-d H:i:s")], ['id' => $id]) : UserModel::insert($data);
        } catch (\Exception $e) {
            return response()->json(compact('status', 'message'));
        }
    }

    public function delete($id) {
        $status = true;
        $message = "删除成功";
        try {
            UserModel::update(['state'=> 8, 'update_at' => date("Y-m-d H:i:s")], ['id' => $id]);
        } catch (\Exception $e) {
            $status = false;
            $message = "操作失败,信息:" . $e->getMessage();
        }

        return response()->json(compact('status', 'message'));
    }

}
